import tinymce from 'tinymce/tinymce'
import { v4 as uuid } from 'uuid'
import { checkBeforeInsert } from '@/utils/helpers'
import { Message } from 'element-ui'

tinymce.PluginManager.add('figurenote', function (editor) {

  function getNumber(node, dataLang = 'zh') {
    const prev = node.previousElementSibling
    const number = prev?.dataset?.number
    const lang = prev?.dataset?.lang
    if (!prev || !prev.classList?.contains?.('figure_note') || !number || lang !== dataLang) return 1
    return parseInt(number) + 1
  }

  // 刷新紧邻的图注编号
  function resetSiblingsNumber(node) {
    function walk(next) {
      if (!next) return
      if (next.classList?.contains?.('figure_note') && node.dataset.lang === next.dataset.lang ) {  
        const number = getNumber(next, next.dataset.lang)
        editor.dom.setAttribs(next, {
          'data-number': number
        })
        if(next.nextElementSibling) {
          walk(next.nextElementSibling)
        }
      }
    }
    if (node?.nextElementSibling) {
      walk(node.nextElementSibling)
    }
  }

  editor.on('keyup', (event) => {
    const node = editor.selection.getNode()
    const prevNode = node.previousSibling
    const _classMatch = prevNode?.classList?.contains?.('figure_note')
    if (!_classMatch) return
    if ("Enter" === event.key) {
      console.log('---PluginManager figurenote keyup Enter ---')
      // 从示例x所在行按住enter，下一行示例x的编号+1
      const number = getNumber(node, node.dataset.lang)
      editor.dom.setAttribs(node, {
        'class': prevNode.className,
        'data-type': 'figure_note',
        'data-number': number,
        'data-id': uuid(),
        'data-share-id': uuid(),
        'data-note-id': uuid(),
        'data-lang': prevNode.dataset.lang
      })
      // 重置紧邻的连续编号
      resetSiblingsNumber(node)
    }

    if (event.key === 'Delete' || event.key === 'Backspace') {
      console.log(`---PluginManager figurenote keyup ${event.key} ---`)
      // 删除了一行，重置后面的连续编号
      resetSiblingsNumber(prevNode || node)
    }
  })

  // 添加命令
  editor.addCommand('toggleFigureNote', (ui, option) => {    
    const node = editor.selection.getNode()
    // 图注只能存在于图片和图题之间
    const ancestor = editor.dom.getParent(node, 'div.data-content-image-wrapper')
    if (!ancestor) {
      return Message.warning({
        message: `请在图结构化块内容中添加图注`,
        showClose: true
      })
    }
    const { numbered, dataLang } = option
    const action = 'figure_note'
    // 当前行是空的P标签，将其变为图注, 否则就在下一行添加图注
    const innerHtml = node.innerHTML.replace(/[\u200B-\u200D\uFEFF]/g, "")
    const classMatch = node.classList.contains('image-wrapper') && !innerHtml.includes('<img')
    if (node.nodeName === 'P' && (innerHtml === '' || classMatch)) {
      editor.dom.removeAllAttribs(node)
      editor.dom.setAttribs(node, {
        'class': action + ' ' + dataLang,
        'data-type': action,
        'data-id': uuid(),
        'data-share-id': uuid(),
        'data-note-id': uuid(),
        'data-lang': dataLang
      })
      if (numbered) {
        const number = getNumber(node, dataLang)
        editor.dom.setAttribs(node, { 'data-number': number } )
      }
      node.innerHTML = '<br>'
    }
    else {
      let configs = {
        'data-type': action,
        'class': action + ' ' + dataLang,
        'data-id': uuid(),
        'data-share-id': uuid(),
        'data-note-id': uuid(),
        'data-lang': dataLang
      }
      const content = editor.dom.create('p', configs, '<br>')
      // 图注只能添加在图片之后
      let referredNode = ancestor.querySelector('p.image-wrapper')
      const existingNotes = ancestor.querySelectorAll('p.figure_note.' + dataLang)
      if (existingNotes?.length > 0) {
        referredNode = existingNotes[existingNotes.length - 1]
      } else if (dataLang === 'en') {
        // 英文图注添加在最后一个中文图注之后
        const existingNotesZh = ancestor.querySelectorAll('p.figure_note.zh')
        if (existingNotesZh?.length > 0) {
          referredNode = existingNotesZh[existingNotesZh.length - 1]
        }
      }
      editor.dom.insertAfter(content, referredNode)
      editor.selection.setCursorLocation(content, 0)
      if (numbered) {
        content.setAttribute('data-number', getNumber(content, dataLang))
        // 刷新后面的图注编号
        resetSiblingsNumber(content)
      }
    }
  })

  const iconStr = `
  <svg width="24px" height="25px" viewBox="0 0 24 25" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <g id="页面-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
      <g transform="translate(-1472.000000, -161.000000)" fill="#000000" fill-rule="nonzero">
          <g id="tool" transform="translate(16.000000, 149.500000)">
              <g id="编组-2" transform="translate(190.000000, 8.000000)">
                  <g id="图注" transform="translate(1266.000000, 3.500000)">
                      <rect id="矩形" opacity="0" x="0" y="0.5" width="24" height="24"></rect>
                      <path d="M12.9049006,12.4361506 L11.1919744,14.6202415 L10.2870739,13.4665483 C10.2166193,13.3762784 10.0801136,13.3762784 10.0096591,13.4665483 L7.81235795,16.2671165 C7.72208807,16.3816051 7.80355114,16.5511364 7.95106534,16.5511364 L16.0511364,16.5511364 C16.1986506,16.5511364 16.2801136,16.3816051 16.1898438,16.2671165 L13.184517,12.4361506 C13.1118608,12.3458807 12.9753551,12.3458807 12.9049006,12.4361506 L12.9049006,12.4361506 Z M8.65340909,10.9588068 C8.65340909,11.445194 9.04770377,11.8394886 9.53409091,11.8394886 C10.020478,11.8394886 10.4147727,11.445194 10.4147727,10.9588068 C10.4147727,10.4724197 10.020478,10.078125 9.53409091,10.078125 C9.04770377,10.078125 8.65340909,10.4724197 8.65340909,10.9588068 Z M19.5430398,7.58139205 L14.8049716,2.84332386 C14.6728693,2.71122159 14.4945312,2.63636364 14.3073864,2.63636364 L4.95454545,2.63636364 C4.56484375,2.63636364 4.25,2.95120739 4.25,3.34090909 L4.25,21.6590909 C4.25,22.0487926 4.56484375,22.3636364 4.95454545,22.3636364 L19.0454545,22.3636364 C19.4351562,22.3636364 19.75,22.0487926 19.75,21.6590909 L19.75,8.08117898 C19.75,7.89403409 19.675142,7.71349432 19.5430398,7.58139205 Z M18.125142,8.40482955 L13.9815341,8.40482955 L13.9815341,4.26122159 L18.125142,8.40482955 Z M18.1647727,20.7784091 L5.83522727,20.7784091 L5.83522727,4.22159091 L12.484375,4.22159091 L12.484375,8.97727273 C12.484375,9.48806818 12.8982955,9.90198864 13.4090909,9.90198864 L18.1647727,9.90198864 L18.1647727,20.7784091 Z" id="形状"></path>
                  </g>
              </g>
          </g>
      </g>
  </g>
</svg>
`
  editor.ui.registry.addIcon('figurenoteIcon', iconStr);
  return (
    editor.ui.registry.addMenuButton('figurenote', {
      tooltip: '图注',
      icon: 'figurenoteIcon',
      fetch: function (callback) {
        callback([
          {
            type: 'menuitem',
            text: '图注',
            onAction: function () {
              if (!checkBeforeInsert('figure_note')) return
              editor.execCommand('toggleFigureNote', false, { numbered: false, dataLang: 'zh' })
            }
          },
          {
            type: 'menuitem',
            text: '图注X',
            onAction: function () {
              if (!checkBeforeInsert('figure_note')) return
              editor.execCommand('toggleFigureNote', false, { numbered: true, dataLang: 'zh' })
            }
          }
        ])
      }
    }),
    {
      getMetadata: function () {
        return {
          name: '图注',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})
